package com.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDao {
	//获得连接
	public Connection getConnection() {
		try {
			//web项目必须要写
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		
		Connection conn=null;
		try {
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC","root","104117");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	
	}
	
	//关闭资源
	public void close(AutoCloseable a) {
		if(a!=null) {
			try {
				a.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	//动态执行给定的sql语句
	public void executeSql(String sql,Object...objs) {
		Connection conn=this.getConnection();
		PreparedStatement ps=null;
		try {
			ps=conn.prepareStatement(sql);
			//设置参数
			for(int i=0;i<objs.length;i++) {
				ps.setObject(i+1, objs[i]);
			}
			ps.execute();
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			this.close(ps);
			this.close(conn);
		}
		
	}
	
	
	
	
	
	//执行一条查询语句，将返回结果封装到List中，每条记录对应一个Map
	public List<Map<String,Object>> executeQuery(String sql,Object...objs){
	 List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
	 Connection conn=this.getConnection();
	 PreparedStatement ps=null;
	 ResultSet rs=null;
	 try {
		 ps=conn.prepareStatement(sql);
		 for(int i=0;i<objs.length;i++) {
			 ps.setObject(i+1, objs[i]);
		 }
		 rs=ps.executeQuery();
		 ResultSetMetaData rsmd=rs.getMetaData();
		 while(rs.next()) {
			 Map<String,Object> map=new HashMap<String,Object>();
			 for(int i=1;i<=rsmd.getColumnCount();i++) {
				 map.put(rsmd.getColumnLabel(i), rs .getObject(i));
			 }
			 list.add(map);
		 }
		 
	 }catch(Exception e) {
		 e.printStackTrace();
	 }finally {
		 this.close(rs);
		 this.close(ps);
		 this.close(conn);
	 }
	 return list;
	}
	
}
